package com.zx.mes.upms.hyl.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.mes.hyl.controller.BaseMethod;
import com.zx.mes.hyl.pagemodel.PageParam;
import com.zx.mes.hyl.response.ObjectRestResponse;
import com.zx.mes.hyl.response.TableResultResponse;
import com.zx.mes.upms.hyl.entity.Permission;
import com.zx.mes.upms.hyl.entity.RolePermission;
import com.zx.mes.upms.hyl.service.PermissionService;
import com.zx.mes.upms.hyl.service.RolePermissionService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 权限标识表 前端控制器
 * </p>
 *
 * @author 华云龙
 * @since 2019-02-15
 */
@RestController
@RequestMapping("/permission")
public class PermissionController extends BaseMethod<PermissionService, Permission> {

    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * 使用要求:所有的表都必需有唯一key值,且名称为 REFLECTION_FIELD_NAME (id)
     *
     * @param entity 实体类(pojo)
     * @return ObjectRestResponse
     */
    @PreAuthorize("hasAuthority('back:permission:save')")
    @ApiOperation(value = "添加一笔数据", notes = "根据id自生成(数据库),还是前端生成(自身成36位)")
    @PostMapping(value = "/add")
    public ObjectRestResponse<Permission> save(@RequestBody Permission entity) {
        entity.setId(baseControllerExt.getUUID())
                .setCreateTime(LocalDateTime.now()).setUpdateTime(LocalDateTime.now());
        return super.add(entity);
    }

    @PreAuthorize("hasAuthority('back:permission:query')")
    @ApiOperation(value = "根据所传id(数据库表的主键必需是id才能用)")
    @GetMapping(value = "getOne/{id}")
    public ObjectRestResponse<Permission> getById(@ApiParam("id 是数据库的唯一主键") @PathVariable String id) {
        return super.get(id);
    }

    /**
     * {
     * "status": 200,
     * "message": "数据更新成功!",
     * "data": null,
     * "rel": true
     * }
     *
     * @param entity 对应实体类
     * @return ObjectRestResponse
     */
    @PreAuthorize("hasAuthority('back:permission:update')")
    @ApiOperation(value = "单笔更新操作", notes = "必需根据id来更新")
    @PutMapping(value = "update")
    public ObjectRestResponse<Permission> updateByEntity(@RequestBody Permission entity) {
        entity.setUpdateTime(LocalDateTime.now());
        return super.update(entity);
    }

    @PreAuthorize("hasAuthority('back:permission:delete')")
    @ApiOperation(value = "单笔删除操作", notes = "必需根据id来删除")
    @DeleteMapping(value = "delete/{id}")
    public ObjectRestResponse<Permission> del(@PathVariable String id) {
        /// 删除权限时要考虑 权限与角色的中间表
        /// 1.删除角色权限中间表
        this.rolePermissionService.remove(new QueryWrapper<RolePermission>()
                .lambda().eq(RolePermission::getPermissionId, id));
        /// 2.再删除权限表中的数据
        return super.remove(id);
    }

    @PreAuthorize("hasAuthority('back:permission:query')")
    @ApiOperation(value = "获取所有的数据", notes = "一般不推荐使用,小数据量可以")
    @GetMapping(value = "/all")
    public List<Permission> getAll() {
        return super.all();
    }

    @PreAuthorize("hasAuthority('back:permission:query')")
    @ApiOperation(value = "分页操作", notes = "params HashMap example = \"page=1&limit=5\"")
    @SuppressWarnings({"unchecked"})
    @GetMapping(value = "/page")
    public TableResultResponse page(@RequestParam Map<String, Object> params, Permission entity) {
        TableResultResponse.Builder<Permission> builder = new TableResultResponse.Builder();
        PageParam extPageParams = this.baseControllerExt.getPageParams(params);
        List<Permission> list = this.biz.page(new Page((long) extPageParams.getPage(), (long) extPageParams.getLimit()),
                new QueryWrapper<Permission>()
                        .lambda()
                        .eq(Permission::getLevel, 1).eq(Permission::getType, 1)).getRecords();
        if (null != list && list.size() != 0) {
            builder.message("分页查询结果")
                    .total((long) this.biz.count(
                            new QueryWrapper<Permission>()
                                    .lambda()
                                    .eq(Permission::getLevel, 1).eq(Permission::getType, 1)
                    ))
                    .page((long) extPageParams.getPage()).rows(list);
        } else {
            builder.message("无数据").page(0L).rows(null);
        }

        return builder.build();
    }


    /**
     * 获取第一层之后,下面的直接根据id寻找子数据
     *
     * @param id permission id
     * @return response
     */
    @GetMapping("/getLazyPermissionById")
    public TableResultResponse<Permission> getLazyPermissionById(@RequestParam Map<String, Object> params, String id) {
        TableResultResponse.Builder<Permission> response = new TableResultResponse.Builder<>();
        PageParam extPageParams = this.baseControllerExt.getPageParams(params);
        List<Permission> permissions = this.biz.page(new Page((long) extPageParams.getPage(), (long) extPageParams.getLimit()),
                new QueryWrapper<Permission>().lambda().eq(Permission::getPid, id)).getRecords();
        response.message("数据获取成功!").rows(permissions).total(this.biz.count(
                new QueryWrapper<Permission>()
                        .lambda().eq(Permission::getPid, id)));
        return response.build();
    }


    /**
     * 判断某个权限下面是否有子权限
     *
     * @param id 权限id
     * @return response
     */
    @GetMapping("/getPermissionById")
    public TableResultResponse<Permission> getPermissionById(String id) {
        TableResultResponse.Builder<Permission> response = new TableResultResponse.Builder<>();
        List<Permission> permissions = this.biz.list(new QueryWrapper<Permission>().lambda().eq(Permission::getPid, id));
        response.message("数据获取成功!").rows(permissions).total(permissions.size());
        return response.build();
    }
}

